package edu.snake.implement.service;

import edu.snake.core.model.character.Character;
import edu.snake.core.service.LiveOrDieService;
import edu.snake.core.utils.Pair;
import edu.snake.implement.model.CharacterName;
import edu.snake.implement.utils.PairBoolean;
import edu.snake.implement.utils.PairCharacterName;

import java.util.HashMap;
import java.util.Map;


public class LiveOrDieServiceImpl implements LiveOrDieService {

    private Map<Pair<CharacterName>, Pair<Boolean>> rulesMap;

    public LiveOrDieServiceImpl() {
        initialize();
    }

    private void initialize() {
        rulesMap = new HashMap<Pair<CharacterName>, Pair<Boolean>>();
        rulesMap.put(new PairCharacterName(CharacterName.SNAKE_HEAD, CharacterName.FROG), new PairBoolean(true, false));
        rulesMap.put(new PairCharacterName(CharacterName.SNAKE_HEAD, CharacterName.SNAKE), new PairBoolean(false, false));
        rulesMap.put(new PairCharacterName(CharacterName.SNAKE_HEAD, CharacterName.SNAKE_TAIL), new PairBoolean(false, false));
        rulesMap.put(new PairCharacterName(CharacterName.SNAKE, CharacterName.BORDER), new PairBoolean(false, false));
    }

    @Override
    public Pair<Boolean> calculateLiveOrDie(Pair<Character> pair) {
        CharacterName first;
        CharacterName second;
        if (pair.getFirst() != null) {
            first = pair.getFirst().getName();
        } else {
            first = CharacterName.EMPTY;
        }
        if (pair.getSecond() != null) {
            second = pair.getSecond().getName();
        } else {
            second = CharacterName.EMPTY;
        }

        Pair<Boolean> result = rulesMap.get(new PairCharacterName(first, second));
        if (result == null) {
            return new PairBoolean(true, true);
        }
        pair.getFirst().setAlive(result.getFirst());
        pair.getSecond().setAlive(result.getSecond());
        return result;
    }
}
